import useSelfState from './useSelfState'
import {unstable_scheduleCallback, unstable_shouldYield} from './scheduler/index'
import { useEffect } from 'react'
import { ImmediatePriority, LowPriority, NormalPriority, UserBlockingPriority } from './scheduler/priotities'

export default function App() {
  const [counter, setCounter] = useSelfState(1000)

  function normalHandler() {
    setCounter(counter + 1, {})
  }

  function mergeHandler() {
    setCounter(counter + 1, {})
    setCounter(counter + 2, {})
    setCounter(counter + 3, {})
    setCounter(counter + 4, {})
  }

  function debounceHandler() {
    setCounter(counter + 6, {debounce: true})
  }


  function A(isTimeout: boolean) {
    const currentTime = performance.now()
    while(performance.now() - currentTime < 8) {
    }
    console.log(`A didTimeout: ${isTimeout}`)
  }

  function B(isTimeout: boolean) {
    const currentTime = performance.now()
    while(performance.now() - currentTime < 3) {}
    console.log(`B didTimeout: ${isTimeout}`)
  }

  function C(isTimeout: boolean) {
    const currentTime = performance.now()
    while(performance.now() - currentTime < 7) {}
    console.log(`C didTimeout: ${isTimeout}`)
  }
  function D(isTimeout: boolean) {
    const currentTime = performance.now()
    while(performance.now() - currentTime < 4) {}
    console.log(`D didTimeout: ${isTimeout}`)
  }
  function E(isTimeout: boolean) {
    const currentTime = performance.now()
    while(performance.now() - currentTime < 10) {}
    console.log(`E didTimeout: ${isTimeout}`)
  }

  useEffect(() => {
    const tasks: any[] = [
      ["1", 3],
      ["2", 3],
      ["3", 5],
      ["4", 7],
      ["5", 9],
    ];

    function node_task() {
      console.log('--开始执行任务--')
      var task
      while(task = tasks.shift()) {
        var now = performance.now()
        // 卡住执行
        while(performance.now() - now < task[1]) {}
        console.log(task[0], '小任务执行完毕')
        if (unstable_shouldYield()) {
          console.log('执行超过了 5ms，中断执行')
          return node_task
        }
      }
    }
    
    unstable_scheduleCallback(NormalPriority, node_task);
    setTimeout(() => {
      unstable_scheduleCallback(ImmediatePriority, () => {
        console.log('我是高优先级插队')
      });
    }, 8)
  }, [])

  return (
    <div>
      hello {counter}
      <button onClick={normalHandler}>同步执行</button>
      <button onClick={mergeHandler}>异步执行</button>
      <button onClick={debounceHandler}>打断执行</button>
    </div>
  )
}

// setCounter -> setState

// 4次 setCounter -> setState

// 多次连续点击 -> setState 防抖

// setState -> 多个函数 Fiber 我已经执行了一部分 Fiber task

// 节流
// 防抖

// 1000项目 -> 300 -！-> DOM 操作结果

// DOM 渲染 1个状态 1个UI  1000列表项